package com.ms.cmdlinetool;

import java.util.ArrayList;
import java.util.HashMap;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.xpec.c4.db.hibernate.manager.ConfigurationManager;
import com.xpec.c4.db.hibernate.manager.HibernateLogManager;

/**
 * 建立循環表，必須先建立參照的table才能正常執行
 */
public class BuildDatabaseRecycleLogTables {

	public static void main(String[] args) {

		long startTime = System.currentTimeMillis();
		ArrayList<String> failQueries = new ArrayList<String>();

		// 如果一般log尚未建立則不處理建立一般log
		ConfigurationManager.setAutoCreateTables(false);
		try {

			Session session = HibernateLogManager.getSession();

			// 取得所有循環log
			HashMap<String, String> recycleModels = ConfigurationManager.getRecyleModel();

			// 只看tableName，不care ClassName
			for (String tableName : recycleModels.values()) {

				System.out.print("create recycle table from " + tableName);

				// 建立12個月份的表
				for (int month = 1; month <= 12; month++) {

					// 組語法
					String monthTable = tableName + "_" + month;
					String queryStr = "create table if not exists `" + monthTable + "` like `" + tableName + "`;";

					try {
						SQLQuery query = session.createSQLQuery(queryStr);
						query.executeUpdate();
					} catch (Exception e) {
						// 紀錄失敗的語法
						failQueries.add(queryStr);
					}

					System.out.print(".");
				}

				System.out.print("\n");
			}

			HibernateLogManager.destroySessionFactory();
			ConfigurationManager.resetConfigs();

		} catch (HibernateException e) {
			e.printStackTrace();
		}

		long costTime = System.currentTimeMillis() - startTime;
		System.out.println("create recycle log tables finish, cost time " + costTime + " ms");

		if (failQueries.size() > 0) {
			System.out.println("fail queries:");
			for (String query : failQueries) {
				System.out.println(query);
			}
		}
	}


}
